/** 
*
* @author  jiwf 
* @date 创建时间：2016年10月23日 下午4:10:51 
* @version 1.0 
* @since  
*  
*/
package com.xbstar.web;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.internal.bind.JsonAdapterAnnotationTypeAdapterFactory;
import com.xbstar.bean.GroupInfo;
import com.xbstar.bean.RouteInfo;
import com.xbstar.bean.SessionInfo;
import com.xbstar.bean.UserToSessionRela;
import com.xbstar.dao.GroupRepository;
import com.xbstar.dao.OrderRepository;
import com.xbstar.dao.RouteInfoRepository;
import com.xbstar.dao.SessionRepostitory;
import com.xbstar.dao.UserGroupRelationRepository;
import com.xbstar.dao.UserToSessionRelaRepository;
import com.xbstar.tools.BeanUtils;
import com.xbstar.tools.Timer;

@RestController
@RequestMapping("/group")
public class GroupController {
	@Autowired
	GroupRepository groupRe;
	@Autowired
	SessionRepostitory sessionRe;
	@Autowired
	RouteInfoRepository routeRe;
	@Autowired
	UserGroupRelationRepository userGroup2RelationRe;
	@Autowired
	UserToSessionRelaRepository user2SessionRe;
	@Autowired
	OrderRepository orderRe;
	@Autowired
	DataSource dataSource;
	@RequestMapping("/add")
	public String addGroup(@RequestParam("routeId")Long routeId,@RequestParam("name")String name,HttpServletRequest req){
		JSONObject json=new JSONObject();
		GroupInfo groupinfo=new GroupInfo();
		SessionInfo session=new SessionInfo();
		try {
			/**
			 * 目前session与group目前共用所有涉及到的字段值。
			 */
			groupinfo=BeanUtils.copyRequestToObj(groupinfo, req);
			groupinfo.setLunchTime(Timer.getCurrentString());
			groupinfo=groupRe.save(groupinfo);
			//session.setId(groupinfo.getId());
			session.setAffixBelongTo(req.getParameter("affixBelongTo"));
			session.setGroupId(groupinfo.getId());
			session.setSessionBelongTo(groupinfo.getGroupBelongTo());
			session.setRouteId(groupinfo.getRouteId());
			session.setLeaderId(groupinfo.getLeaderId());
			//会话名等于分组名
			session.setName(groupinfo.getName());
			session.setLeaderId(groupinfo.getLeaderId());
			session.setLastMsgTime(System.currentTimeMillis()/1000);
			session=sessionRe.save(session);
			groupinfo.setSessionId(session.getId());
			groupRe.save(groupinfo);
			json.put(UserPackage.STATUS, UserPackage.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			json.put(UserPackage.STATUS, UserPackage.SERVER_ERROR);
		}
		return json.toString();
	}
	@RequestMapping("/edit")
	public String addGroup(@RequestParam("id")Long groupId,HttpServletRequest req){
		JSONObject json=new JSONObject();
		GroupInfo group=groupRe.findOne(groupId);
		if(group==null){
			json.put(UserPackage.STATUS, UserPackage.EMPTY);
		}else{
			GroupInfo newgroup=new GroupInfo();
			try {
				newgroup=BeanUtils.copyRequestToObj(newgroup, req);
				group=BeanUtils.merge(group, newgroup);
				group=groupRe.save(group);
				SessionInfo olerSession=sessionRe.findOne(group.getSessionId());
				SessionInfo session=new SessionInfo();
				session.setAffixBelongTo(req.getParameter("affixBelongTo"));
				session.setGroupId(group.getId());
				session.setSessionBelongTo(group.getGroupBelongTo());
				session.setRouteId(group.getRouteId());
				//会话名等于分组名
				session.setName(group.getName());
				session.setLeaderId(group.getLeaderId());
				//session如果没有创建则重新创建
				if(olerSession==null){
					session.setLastMsgTime(System.currentTimeMillis()/1000);
				}else{
					session.setId(group.getSessionId());
					session=BeanUtils.merge(olerSession, session);
				}
				session=sessionRe.save(session);
				group.setSessionId(session.getId());
				groupRe.save(group);
				json.put(UserPackage.STATUS, UserPackage.SUCCESS);
			} catch (Exception e) {
				e.printStackTrace();
				json.put(UserPackage.STATUS, UserPackage.SERVER_ERROR);
			}
		}
		return json.toString();
	}
	@RequestMapping("/del")
	public String addGroup(@RequestParam("id")Long groupId){
		//删除不改变订单状态
		JSONObject json=new JSONObject();
		try {
			GroupInfo group=groupRe.findOne(groupId);
			groupRe.delete(groupId);
			sessionRe.delete(group.getSessionId());
			String sessionBelongTo =group.getGroupBelongTo();
			//删除 user2SeesionRelation
			userGroup2RelationRe.deleteByGroupBelongTo(sessionBelongTo);
			//删除 user2GroupRelation
			user2SessionRe.deleteBySessionBelongTo(sessionBelongTo);
			json.put(UserPackage.STATUS, UserPackage.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			json.put(UserPackage.STATUS, UserPackage.EMPTY);
		}
		return json.toString();
	}
	@RequestMapping("/getall")
	public String getAllGroup(){
		JSONObject json=new JSONObject();
		JSONArray array=new JSONArray();
		List<GroupInfo> groulist=(List<GroupInfo>) groupRe.findAll();
		if(groulist.size()<1){
			json.put(UserPackage.STATUS, UserPackage.EMPTY);
		}else{
			groulist.stream().forEach(group->{
				Connection conn=null;
				JSONObject tjson=new JSONObject();
				tjson=BeanUtils.getAJsonFromObj(group, null);
				RouteInfo routeinfo=routeRe.findOne(group.getRouteId());
				if(routeinfo==null){
					return;
				}
				tjson.put("routeName", routeinfo.getName());
				JSONArray tarray=new JSONArray();
				String sql="SELECT userId,userName,affix_belong_to,id,userImgUrl,nickName,orderId from UserGroupRelationView WHERE groupBelongTo=?";
				
				if(group.getGroupBelongTo()!=null){
					try {
						conn = dataSource.getConnection();
						PreparedStatement ps = conn.prepareStatement(sql);
						ps.setString(1, group.getGroupBelongTo());
						 ResultSet rs = ps.executeQuery();
						 while (rs.next()) {
							 JSONObject ajson=new JSONObject();
							 ajson.put("id", rs.getString("id"));
							 ajson.put("userId", rs.getString("userId"));
							 ajson.put("userName", rs.getString("userName"));
							 ajson.put("affixBelongTo", rs.getString("affix_belong_to"));
							 ajson.put("userImgUrl", rs.getString("userImgUrl"));
							 ajson.put("nickName", rs.getString("nickName"));
							 ajson.put("orderId", rs.getString("orderId"));
							 if(rs.getString("orderId")!=null){
								 Long orderId=Long.parseLong(rs.getString("orderId"));
								 String sql1="SELECT routeName,endTime,startTime FROM userrouteoderview WHERE orderId=?";
								 PreparedStatement ps1 = conn.prepareStatement(sql1);
								 ps1.setLong(1, orderId);
								 ResultSet rs1 = ps1.executeQuery();
								 while (rs1.next()) {
									 ajson.put("orderName", rs1.getString("routeName"));
									 ajson.put("to", rs1.getString("endTime"));
									 ajson.put("from", rs1.getString("startTime"));
								 }
								 rs1.close();
								 ps1.close();
							 }
							 tarray.put(ajson);
						 }
						 rs.close();
						 ps.close();
						 
					} catch (Exception e) {
						e.printStackTrace();
						
					}
				}
				tjson.put("users", tarray);
				array.put(tjson);
				try {
					conn.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			});
			json.put("status", "200");
			json.put(UserPackage.DATA, array);
		}
		return json.toString();
	}
}
